package com.qingge.springboot.controller;


import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.qingge.springboot.common.Constants;
import com.qingge.springboot.entity.*;
import com.qingge.springboot.entity.dto.UpdateDingdanDto;
import com.qingge.springboot.mapper.*;
import com.qingge.springboot.service.IFlowerOrderService;
import com.qingge.springboot.utils.StringUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.qingge.springboot.common.Result;

import com.qingge.springboot.service.IDingdanService;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 格温不受影响
 * @since 2022-05-03
 */
@RestController
@RequestMapping("/dingdan")
public class DingdanController {

    @Resource
    private IDingdanService dingdanService;

    @Autowired
    private IFlowerOrderService iFlowerOrderService;
    @Autowired
    private DingdanMapper mapper;

    @Autowired
    private GwcMapper gwcMapper;

    @Autowired
    private FlowerOrderMapper flowerOrderMapper;

    @Autowired
    private AddressMapper addressMapper;

    @Autowired
    private FlowerMapper flowerMapper;

    @Autowired
    private DingdanMapper dingdanMapper;
    @Transactional
    @PostMapping
    public Result save(@RequestBody FlowerOrderList list) {
        ArrayList<FlowerOrder> flowerOrders = list.getFlowerOrders();
        // 订单名称
        StringBuilder orderName = new StringBuilder();
        int i = 0;
        int len = flowerOrders.size();
        for (FlowerOrder flowerOrder : flowerOrders) {
            orderName.append(flowerOrder.getFname()).
                    append("*").
                    append(flowerOrder.getCnt());
            if (i < len-1) {
                orderName.append(",");
            }
        }
        // 保存订单
        Dingdan dingdan = list.getDingdan();
        dingdan.setDdname(orderName.toString());
        dingdan.setNumber(String.valueOf(UUID.randomUUID()));
        if (StringUtil.isEmptyOrNull(dingdan.getDdmessage())) {
            dingdan.setDdmessage("-");
        }
        mapper.insert(dingdan);
        // 保存订单中的鲜花
        ArrayList<Integer> gwcIds = new ArrayList<>();
        for (FlowerOrder flowerOrder : flowerOrders) {
            flowerOrder.setOid(dingdan.getId());
            Integer gwcId = flowerOrder.getGwcId();
            if (gwcId != null) {
                gwcIds.add(flowerOrder.getGwcId());
            }
            // 鲜花减库存
            Flower flower = flowerMapper.selectById(flowerOrder.getFid());
            int cnt = flower.getCnt()-flowerOrder.getCnt();
            Assert.isTrue(cnt>=0, "库存不足!");
            flower.setCnt(cnt);
            flowerMapper.updateById(flower);
        }
        // 如果是从购物车中下单，则删除购物车对应项
        if (gwcIds.size() > 0) {
            gwcMapper.deleteBatchIds(gwcIds);
        }
        // 自增该订单中 地址的使用次数
        Address address = addressMapper.selectById(dingdan.getAddressId());
        address.setUseTimes(address.getUseTimes()+1);
        addressMapper.updateById(address);
        return Result.success();
    }

    @Transactional
    @GetMapping("/delivery")
    public Result delivery(@RequestParam Integer id) {
        Dingdan dingdan = dingdanMapper.selectById(id);
        // 支付→配送
        if (Constants.STATE_PAYED.equals(dingdan.getState())) {
            dingdan.setState(Constants.STATE_DELIVERY);
        //配送→完成
        } else if (Constants.STATE_DELIVERY.equals(dingdan.getState())) {
            dingdan.setState(Constants.STATE_FINISH);
            dingdan.setEndTime(LocalDateTime.now());
        }
        mapper.updateById(dingdan);
        return Result.success();
    }

    @Transactional
    @PostMapping("/update")
    public Result update(@RequestBody UpdateDingdanDto updateForm) {
        Dingdan dingdan = new Dingdan();
        BeanUtils.copyProperties(updateForm, dingdan);
        if (StringUtil.isEmptyOrNull(dingdan.getDdmessage())) {
            dingdan.setDdmessage("-");
        }
        mapper.updateById(dingdan);
        return Result.success();
    }

    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        dingdanService.removeById(id);
        return Result.success();
    }

    @GetMapping("/cancel")
    public Result cancel(@RequestParam Integer id) {
        updateState(id, Constants.STATE_CANCEL);
        return Result.success();
    }

    public void updateState(Integer id,Integer state) {
        Dingdan dingdan = new Dingdan();
        dingdan.setId(id);
        dingdan.setState(state);
        mapper.updateById(dingdan);
    }

    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        dingdanService.removeByIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result findAll() {
        return Result.success(dingdanService.list());
    }

    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(dingdanService.getById(id));
    }

    @GetMapping("/page")
    public Result findPage(@RequestParam Integer pageNum,
                           @RequestParam Integer pageSize,
                           @RequestParam(required = false) String number,
                           @RequestParam(required = false) Integer uid
                           ) {
        QueryWrapper<Dingdan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(uid !=null,"uid", uid).
                like(!StringUtil.isEmptyOrNull(number),"number", number).
                orderByDesc("id");
        return Result.success(mapper.selectPage(new Page<>(pageNum,pageSize), queryWrapper));
    }

}

